package cn.lopr.im.android.mvp.view.adapters;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.common.Constant;

public class ImageAdapter extends BaseAdapter {

    private Context ctx;
    private List<Integer> emojiIds;
    private LayoutInflater inflater;
    private int baseWidth;
    private int baseHeight;


    public ImageAdapter(Context ctx, List<Integer> emojiIds) {
        this.ctx = ctx;
        this.emojiIds = emojiIds;
        inflater = LayoutInflater.from(ctx);
    }

    public ImageAdapter(Context ctx, List<Integer> emojiIds, int baseWidth) {
        this(ctx, emojiIds);
        this.baseWidth = baseWidth;
        this.baseHeight = baseWidth;
    }

    @Override
    public int getCount() {
        return emojiIds.size();
    }

    @Override
    public Object getItem(int i) {
        return emojiIds.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        emojiHolder holder = null;
        if (view == null) {
            view = inflater.inflate(R.layout.list_item_publish_img, null);
            holder = new emojiHolder();
            holder.emojiImg = view.findViewById(R.id.iv_add_img);
            view.setTag(holder);
        } else {
            holder = (emojiHolder) view.getTag();
        }


        view.setLayoutParams(new ViewGroup.LayoutParams(baseWidth, baseHeight));

        return view;
    }

    public void initKeyTextView(final View ll, final int position) {
        ViewTreeObserver vto2 = ll.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                if (position % Constant.GRIVEW_COLUMN_NUMS == 0) {
                    Constant.GRIVIEW_COLUMN_HEIGHT = 0;
                }
                if (ll.getHeight() > Constant.GRIVIEW_COLUMN_HEIGHT) {
                    Constant.GRIVIEW_COLUMN_HEIGHT = ll.getHeight();
                }
                setHeight(ll, Constant.GRIVIEW_COLUMN_HEIGHT);
            }
        });
    }

    public void setHeight(View ll, int height) {
        ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));

    }

    class emojiHolder {
        ImageView emojiImg;
    }
}
